package com.tcwlkj.uuService.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.tcwlkj.uuService.MyApp;
import com.tcwlkj.uuService.NetWork.HttpCallBack;
import com.tcwlkj.uuService.NetWork.RetrofitUtils;
import com.tcwlkj.uuService.R;
import com.tcwlkj.uuService.adapter.WaitOrderAdapter;
import com.tcwlkj.uuService.model.CommonResponse;
import com.tcwlkj.uuService.model.ImageUrlModel;
import com.tcwlkj.uuService.model.LocationModel;
import com.tcwlkj.uuService.model.OrderModel;
import com.tcwlkj.uuService.model.UpdateMessage;
import com.tcwlkj.uuService.ui.BaseActivity;
import com.tcwlkj.uuService.ui.OrderMapActivity;
import com.tcwlkj.uuService.utils.ChcheUtils;
import com.tcwlkj.uuService.utils.EventCenter;
import com.tcwlkj.uuService.utils.MyRefresh;
import com.tcwlkj.uuService.utils.PreferencesUtils;
import com.tcwlkj.uuService.utils.ToastUtil;
import com.tcwlkj.uuService.utils.Tools;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import butterknife.Bind;
import retrofit2.Call;

import static android.app.Activity.RESULT_OK;

/**
 * Created by Administrator on 2017/9/30 0030.
 */

public class WaitOrder_Fragment extends BaseFragment {

    @Bind(R.id.recyclerview)
    RecyclerView recyclerview;
    @Bind(R.id.refreshLayout)
    TwinklingRefreshLayout refreshLayout;
//    @Bind(R.id.lay_total_empty)
//    LinearLayout lay_total_empty;

    @Bind(R.id.lay_total_code)
    LinearLayout lay_total_code;
    @Bind(R.id.ivRunManCode)
    ImageView ivRunManCode;
    @Bind(R.id.ivUserCode)
    ImageView ivUserCode;


    private ArrayList<OrderModel> modelList = new ArrayList<OrderModel>();
    private WaitOrderAdapter waitOrderAdapter;
    private int pindex = 1;
    @Override
    protected int getLayout() {
        return R.layout.fragment_wait;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerview.setLayoutManager(layoutManager);
        waitOrderAdapter = new WaitOrderAdapter(modelList, getContext());
        recyclerview.setAdapter(waitOrderAdapter);
        MyRefresh.getInstance().getMusic(refreshLayout, false);
        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                modelList.clear();
                pindex = 1;
                getWaitOrder(pindex, true);
                refreshLayout.finishRefreshing();
            }
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pindex++;
                getWaitOrder(pindex, true);
                refreshLayout.finishLoadmore();
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getWaitOrder(pindex, false);
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }
    private Uri uri;
    private static final String fileName = "TongchengImage.jpg";
    private String orderid="0";
    @Override
    protected void onEventComing(EventCenter eventCenter) {
        super.onEventComing(eventCenter);
        if (eventCenter.getEventCode() == 222) {//取消订单
            modelList.clear();
            getWaitOrder(pindex, false);
        } else if (eventCenter.getEventCode() == 111) {//抢单成功
            modelList.clear();
            getWaitOrder(pindex, false);
        } else if (eventCenter.getEventCode() == 333) {//打电话

            checkPermission(new BaseActivity.CheckPermListener() {
                @Override
                public void superPermission() {
                    UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
                    Intent intent = new Intent(); // 意图对象：动作 + 数据
                    intent.setAction(Intent.ACTION_CALL); // 设置动作
                    Uri data = Uri.parse("tel:" + updateMessage.getMessage()); // 设置数据
                    intent.setData(data);
                    startActivity(intent); // 激活Activity组件
                }
            }, R.string.sd, Manifest.permission.CALL_PHONE);
        } else if (eventCenter.getEventCode() == 444) {//已到达
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            UpDateState(updateMessage.getOrderId(), "3");
        } else if (eventCenter.getEventCode() == 555) {//已取件
            checkPermission(new BaseActivity.CheckPermListener() {
                @Override
                public void superPermission() {
                    UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
                    orderid=updateMessage.getOrderId();
                    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                    if (Tools.isExistSd()) {
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), fileName)));
                        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                        StrictMode.setVmPolicy(builder.build());
                        builder.detectFileUriExposure();
                    }
                    startActivityForResult(intent, 1);
                }
            }, R.string.CAMERA, Manifest.permission.CAMERA);
        } else if (eventCenter.getEventCode() == 666) {//已送达||结束排队
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            UpDateState(updateMessage.getOrderId(), "7");
        } else if (eventCenter.getEventCode() == 777) {//已完成
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            finishOrder(updateMessage.getOrderId(),updateMessage.getMessage(),updateMessage.getLng(),updateMessage.getLat());
        } else if (eventCenter.getEventCode() == 888) {//开始排队
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            UpDateState(updateMessage.getOrderId(), "4");
        } else if (eventCenter.getEventCode() == 80) {//打电话 送
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            showDialog(updateMessage.getMessage(), updateMessage.getOrderId(), "联系发货人", "联系收货人");
        } else if (eventCenter.getEventCode() == 81) {//打电话 取
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            showDialog(updateMessage.getMessage(), updateMessage.getOrderId(), "联系取货人", "联系收货人");
        } else if (eventCenter.getEventCode() == 82) {//打电话 买
            showDialogOne(eventCenter.getData().toString(), "联系收货人");
        } else if (eventCenter.getEventCode() == 83) {//打电话 帮
            showDialogOne(eventCenter.getData().toString(), "联系下单人");
        } else if (eventCenter.getEventCode() == 84) {//打电话 排
            showDialogOne(eventCenter.getData().toString(), "联系下单人");
        } else if (eventCenter.getEventCode() == 85) {//地图
            OrderModel orderModel = (OrderModel) eventCenter.getData();
            Intent intent = new Intent(getActivity(), OrderMapActivity.class);
            intent.putExtra("orderModel", orderModel);
            startActivity(intent);
        }else if(eventCenter.getEventCode() == 86){
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            call(updateMessage.getMessage(),updateMessage.getOrderId());
        }else if(eventCenter.getEventCode()==999){//重发验证码
            UpdateMessage updateMessage = (UpdateMessage) eventCenter.getData();
            getcode(updateMessage.getOrderId());
        }else if(eventCenter.getEventCode()==-55){
            if(recyclerview.getScrollState()==recyclerview.SCROLL_STATE_IDLE){
                modelList.clear();
                pindex = 1;
                getWaitOrder(pindex, false);
            }
        }
    }

    private void getcode(String orderid){
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(getActivity(), true).getOrderCode(orderid,"0");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {
                modelList.clear();
                getWaitOrder(pindex, false);
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getcode(orderid);
                } else {
                    ToastUtil.getInstance().show(message);
                    waitOrderAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void call(String phone,String orderId){
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(MyApp.getContext(), false).call(ChcheUtils.getInstance().getDriverDetailModel().getBase().getMobile(),phone,orderId,"0");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {
                checkPermission(new BaseActivity.CheckPermListener() {
                    @Override
                    public void superPermission() {
                        modelList.clear();
                        getWaitOrder(pindex, false);
                        Intent intent = new Intent(); // 意图对象：动作 + 数据
                        intent.setAction(Intent.ACTION_CALL); // 设置动作
                        Uri data = Uri.parse("tel:" + phone); // 设置数据
                        intent.setData(data);
                        startActivity(intent); // 激活Activity组件
                    }
                }, R.string.sd, Manifest.permission.CALL_PHONE);
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    call(phone,orderId);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    /**
     * 定义方法裁剪图片
     */
    public void cutImage(Uri uri, int type) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1.5);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);//剪裁后X的像素
        intent.putExtra("outputY", 150);//剪裁后Y的像素
        intent.putExtra("output", Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone"))); //保存路径me
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, type);
    }
    private String mImage;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode==1){
                checkPermission(new BaseActivity.CheckPermListener() {
                    @Override
                    public void superPermission() {
                        uri = Tools.getImageContentUri(getContext(), new File(Environment.getExternalStorageDirectory(), "/" + fileName));
                        cutImage(uri, 2);
                    }
                }, R.string.sd, android.Manifest.permission.READ_EXTERNAL_STORAGE);
            }else if(requestCode==2){
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "/cutphone")));
                    mImage=Tools.bitmapToBase64(bitmap);
                    uploadImage(mImage,3,"取件拍照",orderid);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void uploadImage(String image,int type,String note,String orderid) {
        Call<CommonResponse<ImageUrlModel>> httpResultCall = RetrofitUtils.getUploadRequest(getActivity(), true).upload("03A79706EC26C73C53018911BD88BC2842DE90808FDCC97E,"+type+"," + PreferencesUtils.getString(MyApp.getContext(), "userID") + ",3,"+orderid+","+note
                , image, "touxiang.jpg");
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<ImageUrlModel>>() {
            @Override
            public void onSuccess(Object t) {
                UpDateState(orderid, "6");
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    ToastUtil.getInstance().show("请重新提交");
                }else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    private void showDialogOne(String phone, String str) {
        final String[] stringItems = {str};
        final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, null);
        dialog.itemTextColor(Color.parseColor("#000000"))
                .itemTextSize(14.5f)
                .cancelText(Color.parseColor("#000000"))
                .cancelTextSize(14.5f)
                .show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        checkPermission(new BaseActivity.CheckPermListener() {
                            @Override
                            public void superPermission() {
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + phone); // 设置数据
                                intent.setData(data);
                                startActivity(intent); // 激活Activity组件
                            }
                        }, R.string.sd, Manifest.permission.CALL_PHONE);
                        break;
                }
                dialog.dismiss();
            }
        });
    }

    private void showDialog(String munber1, String number2, String str1, String str2) {
        final String[] stringItems = {str1, str2};
        final ActionSheetDialog dialog = new ActionSheetDialog(getContext(), stringItems, null);
        dialog.itemTextColor(Color.parseColor("#000000"))
                .itemTextSize(14.5f)
                .cancelText(Color.parseColor("#000000"))
                .cancelTextSize(14.5f)
                .show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        checkPermission(new BaseActivity.CheckPermListener() {
                            @Override
                            public void superPermission() {
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + munber1); // 设置数据
                                intent.setData(data);
                                startActivity(intent); // 激活Activity组件
                            }
                        }, R.string.sd, Manifest.permission.CALL_PHONE);
                        break;
                    case 1:
                        checkPermission(new BaseActivity.CheckPermListener() {
                            @Override
                            public void superPermission() {
                                Intent intent = new Intent(); // 意图对象：动作 + 数据
                                intent.setAction(Intent.ACTION_CALL); // 设置动作
                                Uri data = Uri.parse("tel:" + number2); // 设置数据
                                intent.setData(data);
                                startActivity(intent); // 激活Activity组件
                            }
                        }, R.string.sd, Manifest.permission.CALL_PHONE);
                        break;
                }
                dialog.dismiss();
            }
        });
    }
    private void finishOrder(String OrderId,String yzcode,double lng,double lat){
        LocationModel locationModel = new LocationModel(lng, lat);
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(getActivity(), true).finish(OrderId, PreferencesUtils.getString(MyApp.getContext(), "userID"), yzcode, Tools.javabeanToJson(locationModel));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {
                finish_dialog(OrderId,modelList);
                modelList.clear();
                getWaitOrder(pindex, false);
            }
            @Override
            public void onFail(int code, String message) {
                if(code == 40104){
                    finishOrder(OrderId,yzcode,lng,lat);
                }else{
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    private void UpDateState(String OrderId, String state) {
        LocationModel locationModel = new LocationModel(ChcheUtils.getInstance().getLocationModel().getLng(), ChcheUtils.getInstance().getLocationModel().getLat());
        Call<CommonResponse<Object>> httpResultCall = RetrofitUtils.getRequest(getActivity(), true).state(OrderId, PreferencesUtils.getString(MyApp.getContext(), "userID"), state, Tools.javabeanToJson(locationModel));
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<Object>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<Object> commonResponse = new CommonResponse<Object>();
                modelList.clear();
                getWaitOrder(pindex, false);
            }
            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    UpDateState(OrderId, state);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }

    public void getWaitOrder(int pindex, boolean flag) {
        Call<CommonResponse<ArrayList<OrderModel>>> httpResultCall = RetrofitUtils.getRequest(getActivity(), false).orderlist(PreferencesUtils.getString(MyApp.getContext(), "userID"), -1, 888, pindex, 10);
        httpResultCall.enqueue(new HttpCallBack<CommonResponse<ArrayList<OrderModel>>>() {
            @Override
            public void onSuccess(Object t) {
                CommonResponse<ArrayList<OrderModel>> commonResponse = (CommonResponse<ArrayList<OrderModel>>) t;
                String oridIdList="";
                for(int i=0;i<commonResponse.getData().size();i++){
                    oridIdList=oridIdList+commonResponse.getData().get(i).getID()+",";
                }
                PreferencesUtils.putString(MyApp.getContext(),"oridIdList",oridIdList);
                if (commonResponse.getTotal().equals("0")) {
//                    lay_total_empty.setVisibility(View.VISIBLE);
                    lay_total_code.setVisibility(View.VISIBLE);
                    Glide.with(getActivity()).load(PreferencesUtils.getString(getActivity(), "runManCode")).error(R.mipmap.iv_code).into(ivRunManCode);
                    Glide.with(getActivity()).load(PreferencesUtils.getString(getActivity(), "userCode")).error(R.mipmap.iv_code).into(ivUserCode);
                    recyclerview.setVisibility(View.GONE);
                    EventBus.getDefault().post(new EventCenter<String>(102, commonResponse.getTotal() + ""));
                    return;
                }
                if (flag && modelList.size() >= Integer.parseInt(commonResponse.getTotal())) {
                    ToastUtil.getInstance().show("没有更多数据");
                    return;
                }
                lay_total_code.setVisibility(View.GONE);
                recyclerview.setVisibility(View.VISIBLE);
                modelList.addAll(commonResponse.getData());
                waitOrderAdapter.updateData(modelList);
                EventBus.getDefault().post(new EventCenter<String>(102, commonResponse.getTotal() + ""));
            }

            @Override
            public void onFail(int code, String message) {
                if (code == 40104) {
                    getWaitOrder(pindex, flag);
                } else {
                    ToastUtil.getInstance().show(message);
                }
            }
        });
    }
    private void finish_dialog(String orderid,ArrayList<OrderModel> modelList){
        OrderModel orderModel=new OrderModel();
        for(int i=0;i<modelList.size();i++){
            if(modelList.get(i).getID().equals(orderid)){
                orderModel=modelList.get(i);
            }
        }
        LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.finish_dialog, null);
        PopupWindow popupWindow=new PopupWindow(contentview, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setAnimationStyle(R.style.anim_menu_bottombar);
        backgroundAlpha(0.5f);
        popupWindow.setOnDismissListener(new poponDismissListener());
        contentview.setFocusable(true); // 这个很重要
        contentview.setFocusableInTouchMode(true);

        Button btnDialog=(Button) contentview.findViewById(R.id.btn_dialogover);
        TextView tv_money_dialogover=(TextView) contentview.findViewById(R.id.tv_money_dialogover);
        TextView tv_xiaofei=(TextView) contentview.findViewById(R.id.tv_xiaofei);
        TextView tv_jiajia=(TextView) contentview.findViewById(R.id.tv_jiajia);
        LinearLayout ll_tip= (LinearLayout) contentview.findViewById(R.id.ll_tip);
        LinearLayout ll_jiangli= (LinearLayout) contentview.findViewById(R.id.ll_jiangli);
        LinearLayout ll_peisong= (LinearLayout) contentview.findViewById(R.id.ll_peisong);
        tv_money_dialogover.setText(orderModel.getDriverFreightMoney());
        if(orderModel.getPayUserFeeMoney().equals("0.00元")&&orderModel.getSysAddMoney().equals("0.00元")){
            ll_tip.setVisibility(View.GONE);
        }else if(orderModel.getPayUserFeeMoney().equals("0.00元")){
            ll_jiangli.setVisibility(View.GONE);
        }else if(orderModel.getSysAddMoney().equals("0.00元")){
            ll_peisong.setVisibility(View.GONE);
        }
        tv_xiaofei.setText(orderModel.getPayUserFeeMoney());
        tv_jiajia.setText(orderModel.getSysAddMoney());

        btnDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post(new EventCenter<String>(-10,"完成订单"));
                popupWindow.dismiss();
            }
        });
        View rootview = LayoutInflater.from(getContext()).inflate(R.layout.fragment_wait, null);
        popupWindow.showAtLocation(rootview, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }
    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }
    /**
     * 添加新笔记时弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            backgroundAlpha(1f);
        }

    }

}